import { FlipKeyInfoForSend, FlipService } from "@/popup/services/flip";
import { IMemberFlipInfo, MemberService } from "@/popup/services/member";
import { memberInfo } from "@/popup/stores/member";
import { useUserStore } from "@/popup/stores/user";
import {
  Button,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Radio,
  Spin,
  Tooltip,
} from "antd";
import { useEffect, useMemo, useState } from "react";
import { FlipMode } from "..";

export const FlipRequest = ({
  info,
  setActiveMode,
}: {
  info: memberInfo;
  setActiveMode: (mode: FlipMode) => void;
}) => {
  const { userInfo } = useUserStore();
  const [cost, setCost] = useState<number | undefined>(undefined);
  const [flipInfo, setFlipInfo] = useState<IMemberFlipInfo>({ customs: [] });
  const [question, setQuestion] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [openType, setOpenType] = useState<number>(1);
  const [answerType, setAnswerType] = useState<number>(1);

  const openOptions = [
    {
      label: "公开",
      value: 1,
    },
    {
      label: "私密",
      value: 2,
    },
    {
      label: "匿名",
      value: 3,
    },
  ];
  const answerOptions = [
    {
      label: "文字",
      value: 1,
    },
    {
      label: "语音",
      value: 2,
    },
    {
      label: "视频",
      value: 3,
    },
  ];
  useEffect(() => {
    MemberService.getMemberFlipInfo(
      `${info.memberId}`,
      userInfo?.token || ""
    ).then((res) => {
      setFlipInfo(res);
      console.log(res);
    });
  }, []);
  const minCost = useMemo(() => {
    if (!flipInfo?.customs || flipInfo?.customs?.length === 0) return 50;
    const costMap = flipInfo?.customs?.[answerType - 1];
    if (!costMap) return 999999999999;
    if (openType === 1) {
      return costMap?.normalCost || 0;
    } else if (openType === 2) {
      return costMap?.privateCost || 0;
    } else if (openType === 3) {
      return costMap?.anonymityCost || 0;
    }
  }, [flipInfo, openType, answerType]);

  const handleSendFlip = async () => {
    
    if (!cost) {
      message.error("请输入鸡腿数");
      return;
    }
    if (cost < (minCost || 50)) {
      message.error(`最低${minCost}鸡腿`);
      return;
    }
    if (cost > userInfo?.userInfo?.money) {
      message.error(`鸡腿不足`);
      return;
    }
    setLoading(true);
    try {
        const flipInfo: FlipKeyInfoForSend = {
            memberId: `${info.memberId}`,
            content: question,
            type: openType,
            cost: `${cost}`,
            answerType: answerType,
          };
          const res = await FlipService.sendFlip(flipInfo, userInfo?.token || "");
          if (res) {
            message.success("提问成功");
            setQuestion("");
            setCost(undefined);
            setOpenType(1);
            setAnswerType(1);
            setActiveMode(FlipMode.HISTORY);
          } else {
            message.error("提问失败");
          }
    } catch (error) {
        message.error("提问失败");
    } finally {
        setLoading(false);
    }
  };
  return (
    <Spin spinning={loading}>
      <div style={{ display: "flex", padding: "8px" }}>
        <div style={{ flex: 1 }}>
          <div
            style={{
              fontSize: "14px",
              fontWeight: "bold",
              marginBottom: "8px",
            }}
          >
            提问问题
          </div>
          <Input.TextArea
            showCount
            value={question}
            onChange={(e) => setQuestion(e.target.value)}
            maxLength={200}
            rows={10}
            required={true}
            placeholder="请输入问题"
          />
        </div>
        <div
          style={{
            width: "200px",
            marginLeft: "4px",
            padding: "0 4px",
          }}
        >
          <div
            style={{
              fontSize: "14px",
              fontWeight: "bold",
              marginBottom: "8px",
            }}
          >
            翻牌设置
          </div>
          <div style={{ border: "1px solid #e8e8e8", padding: "8px" }}>
            <Radio.Group
              size="small"
              block
              options={openOptions}
              defaultValue={1}
              optionType="button"
              buttonStyle="solid"
              onChange={(e) => {
                setOpenType(e.target.value);
              }}
            />
            <Radio.Group
              block
              options={answerOptions}
              defaultValue={1}
              size="small"
              style={{ margin: "8px 0" }}
              optionType="button"
              buttonStyle="solid"
              onChange={(e) => {
                setAnswerType(e.target.value);
              }}
            />
            <div>输入鸡腿数</div>
            <InputNumber
              max={Math.max(userInfo?.userInfo?.money, minCost || 0)}
              min={minCost}
              value={cost}
              onChange={(value) => setCost(value || undefined)}
              style={{ width: "100%" }}
              placeholder={`最低${minCost}鸡腿`}
            />
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                width: "100%",
                marginTop: "8px",
              }}
            >
              <Popconfirm
                placement="topLeft"
                title={"确认"}
                description={`确认花费${cost}鸡腿，向${info.memberName}提问吗`}
                okText="Yes"
                cancelText="No"
                onConfirm={() => {
                  handleSendFlip();
                }}
              >
                <Tooltip title={!cost ? "请输入鸡腿数" : ""}>
                  <Button disabled={!cost} type="link">
                    提问
                  </Button>{" "}
                </Tooltip>
              </Popconfirm>
            </div>
          </div>
        </div>
      </div>
    </Spin>
  );
};
